package com.example.demo.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.entity.Account;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.AccountMapper;
import com.example.demo.service.UserService;
import com.example.demo.dto.UserDTO;
import com.example.demo.vo.UserVO;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.demo.entity.table.UserTableDef.USER;
import static com.example.demo.entity.table.AccountTableDef.ACCOUNT;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUser(UserDTO userDTO) {
        // JDK8友好的时间处理
        userDTO.setCreateTime(new Date());

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        // 保存用户
        userMapper.insert(user);

        // 创建账户
        Account account = new Account();
        account.setUserId(user.getId());
        account.setBalance(BigDecimal.ZERO);
        account.setCreateTime(new Date());
        accountMapper.insert(account);

        // 更新用户的账户ID
        user.setAccountId(account.getId());
        userMapper.update(user);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectOneById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public Page<User> paginateUser(int pageNumber, int pageSize, String keyword) {
        QueryWrapper queryWrapper = QueryWrapper.create();

        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.where(USER.NAME.like("%" + keyword + "%"));
        }

        queryWrapper.and(USER.IS_DELETED.eq(false))
                .orderBy(USER.ID.desc());

        return userMapper.paginate(pageNumber, pageSize, queryWrapper);
    }

    @Override
    public List<UserVO> listUsersWithBalance() {
        List<User> users = userMapper.selectListByQuery(
                QueryWrapper.create()
                        .select(USER.ID, USER.NAME, USER.AGE, ACCOUNT.BALANCE)
                        .from(USER)
                        .leftJoin(ACCOUNT).as("a").on(USER.ACCOUNT_ID.eq(ACCOUNT.ID))
                        .where(USER.IS_DELETED.eq(false)));

        // JDK8兼容的转换方式
        return users.stream().map(user -> {
            UserVO vo = new UserVO();
            vo.setId(user.getId());
            vo.setName(user.getName());
            vo.setAge(user.getAge());
            vo.setCreateTime(user.getCreateTime());
            if (user.getAccount() != null) {
                vo.setBalance(user.getAccount().getBalance());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<User> getUsersByDepartment(String deptName) {
        return userMapper.selectUsersByDepartment(deptName);
    }
}